import json
import random

from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.core.mail import send_mail
from django.shortcuts import render, redirect
# Create your views here.
from django.views import View
from django import http
import re

from carts.utils import merge_cookie_redis_cart
from goods.models import SKU
from meiduo_mall.libs.yuntongxun.sms import CCP
from meiduo_mall.utils.login import MyloginRequiredMiXinView
from meiduo_mall.utils.response_code import RET
from verifications import contants
from .models import User, Address
from django_redis import get_redis_connection

from django.views.decorators.csrf import csrf_exempt
class RegisterView(View):

    def get(self, request):
        return render(request, "register.html")


    def post(self, request):
        # 获取提交表单信息
        user_name = request.POST.get("user_name")
        pwd = request.POST.get("pwd")
        cpwd = request.POST.get("cpwd")
        mobile = request.POST.get("phone")
        msg_code = request.POST.get("msg_code")
        allow = request.POST.get("allow")
        sms_code = msg_code



        # 判空
        if not all([user_name, pwd, cpwd, mobile, msg_code, allow]):
            return http.HttpResponseForbidden("请将信息填写完整")

        # if not all([user_name, pwd, cpwd, phone, msg_code, allow]):
        #     return http.HttpResponseForbidden("参数不全")


        # 校验密码是否一致
        if pwd != cpwd:
            return http.HttpResponseForbidden("密码不一致")
        # 校验手机号是否合法
        if not re.match(r"1[3-9]\d{9}", mobile):
            return http.HttpResponseForbidden("手机号码输入有误")

            # 2,3 手机号格式校验


        # 校验短信验证码
        redis_conn= get_redis_connection("code")
        sms_code_redis = redis_conn.get("sms_code_%s" % mobile)
        sms_code_redis = sms_code_redis.decode()
        print(sms_code)
        print(sms_code_redis)

        if sms_code != sms_code_redis:

            return http.HttpResponseForbidden("短信验证码输入有误")


        # 校验是否同意协议
        if allow != "on":
            return http.HttpResponseForbidden("请同意协议")


        # 校验无误，将用户信息储存在数据库中
        user = User.objects.create_user(username=user_name, password=pwd, mobile=mobile)


        return redirect('/index')


class CheckUserName(View):
    # 判断数据库中是否存在该数据
    def get(self, request, username):
        count = User.objects.filter(username=username).count()


        return http.JsonResponse({"count": count})


class Checkphone(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()

        return http.JsonResponse({"count": count})




class LoginView(View):
    def get(self, request):
        return render(request, "login.html")

    def post(self, request):
        username = request.POST.get("username")
        password = request.POST.get("pwd")
        remembered = request.POST.get("remembered")

        if not all([username, password]):
            return http.HttpResponseForbidden("参数不全")

        if not re.match(r"^[a-zA-Z0-9_-]{5,20}$", username):
            return http.HttpResponseForbidden("用户名格式有误")

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden("密码格式有误")

        user = authenticate(request, username=username, password=password)

        if not user:
            return http.HttpResponseForbidden("账号或密码错误")


        # 登陆状态保持
        login(request, user)

        # 设置登陆状态保持时间（默认2个星期）
        if remembered == "on":
            request.session.set_expiry(3600*24*2)
        else:
            request.session.set_expiry(0)

        response = redirect('/')
        response.set_cookie("username", user.username, 3600*24*2)
        response = merge_cookie_redis_cart(request, user, response)

        return response



class LogoutUserView(View):
    def get(self, request):
        logout(request)

        response = redirect("/")
        response.delete_cookie("username")
        return response



# is_authenticated
class UserCenterView(MyloginRequiredMiXinView):
    def get(self, request):
        context = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
            "email_active": request.user.email_active
                                }

        return render(request, "user_center_info.html", context=context)





from meiduo_mall.utils.email import generate_verify_url, decode_token
from celery_tasks.email.tasks import send_verify_url

class EmailSendView(MyloginRequiredMiXinView):
    def put(self, request):
        dict_data = json.loads(request.body.decode())
        email = dict_data.get("email")

        if not email:
            return http.HttpResponseForbidden("参数不全")

        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):

            return http.HttpResponseForbidden("邮箱格式错误")

        verify_url = generate_verify_url(request.user)

        # send_mail(subject="美多商城邮箱激活",
        #           message=verify_url,
        #           from_email=settings.EMAIL_FROM,
        #           recipient_list=["kusuriya_wasabi@163.com"])
        send_verify_url.delay(verify_url, email)

        request.user.email = email
        request.user.save()

        return http.JsonResponse({"code": RET.OK, "errmsg": "ok"})


class EmailActiveView(View):
    def get(self, request):

        token = request.GET.get("token")

        if not token:
            return http.HttpResponseForbidden("token丢失")

        user = decode_token(token)

        if not user:
            return http.HttpResponseForbidden("token过期")

        user.email_active = True
        user.save()

        return redirect("/info")


class AddressView(MyloginRequiredMiXinView):
    def get(self, request):
        addresses = request.user.addresses.filter(is_deleted=False)
        addresses_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email,
            }
            addresses_list.append(address_dict)

        context ={
            "addresses": addresses_list,
            "default_address_id": request.user.default_address_id
        }




        return render(request, "user_center_site.html", context=context)


class AddressCreateView(MyloginRequiredMiXinView):
    def post(self, request):
        dict_data = json.loads(request.body.decode())
        title = dict_data.get("title")
        receiver = dict_data.get("receiver")
        province_id = dict_data.get("province_id")
        city_id = dict_data.get("city_id")
        district_id = dict_data.get("district_id")
        place = dict_data.get("place")
        mobile = dict_data.get("mobile")
        tel = dict_data.get("tel")
        email = dict_data.get("email")

        if not all([title, receiver, province_id, city_id, district_id, place, mobile, tel, email]):
            return http.HttpResponseForbidden("canshubuquan")

        dict_data["user"] = request.user
        address = Address.objects.create(**dict_data)

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email,

        }

        return http.JsonResponse({"code": RET.OK, "address": address_dict})


class AddressUpdataView(MyloginRequiredMiXinView):
    def post(self, request, address_id):
        dict_data = json.loads(request.body.decode())
        title = dict_data.get("title")
        receiver = dict_data.get("receiver")
        province_id = dict_data.get("province_id")
        city_id = dict_data.get("city_id")
        district_id = dict_data.get("district_id")
        place = dict_data.get("place")
        mobile = dict_data.get("mobile")
        tel = dict_data.get("tel")
        email = dict_data.get("email")

        if not all([title, receiver, province_id, city_id, district_id, place, mobile, tel, email]):
            return http.HttpResponseForbidden("canshubuquan")
        
        address = Address.objects.get(address_id=address_id)
        address.title = title
        address.receiver = receiver
        address.province_id = province_id
        address.city_id = city_id
        address.district_id = district_id
        address.place = place
        address.mobile = mobile
        address.tel = tel
        address.email = email
        address.save()

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email}

        return http.JsonResponse({"code": RET.OK, "address": address_dict})

    def delete(self, request, address_id):
        address = Address.objects.get(id=address_id)
        address.is_deleted = True
        address.save()

        return http.JsonResponse({"code": RET.OK})


class AddressDefaultView(MyloginRequiredMiXinView):
    def put(self, request, address_id):
        request.user.default_address_id = address_id
        request.user.save()

        return http.JsonResponse({"code": RET.OK})


class AddressTitleView(MyloginRequiredMiXinView):
    def put(self, request, address_id):
        dict_data = json.loads(request.body.decode())
        title = dict_data.get("title")

        if not title:
            return http.HttpResponseForbidden("请填写修改的标题")


        ret = Address.objects.filter(id=address_id).update(title=title)
        if ret == 0:
            return http.HttpResponseForbidden("修改失败")





        return http.JsonResponse({"code": RET.OK})


class PasswordChangeView(MyloginRequiredMiXinView):
    def get(self, request):
        return render(request, "user_center_pass.html")

    def post(self, request):
        old_pwd = request.POST.get("old_pwd")
        new_pwd = request.POST.get("new_pwd")
        new_cpwd = request.POST.get("new_cpwd")

        if not all([old_pwd, new_pwd, new_cpwd]):
            return http.HttpResponseForbidden("参数不全")

        if not re.match(r'^[0-9A-Za-z]{8,20}$', old_pwd):
            return http.HttpResponseForbidden("旧密码格式有误")

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_pwd):
            return http.HttpResponseForbidden("旧密码格式有误")

        if not request.user.check_password(old_pwd):
            return http.HttpResponseForbidden("旧密码输入错误")

        if new_pwd != new_cpwd:
            return http.HttpResponseForbidden("2次密码请一致")

        request.user.set_password(new_pwd)
        request.user.save()

        logout(request)
        response = redirect('/login')
        response.delete_cookie("username")
        return response


class UserBrowserHistoryView(MyloginRequiredMiXinView):
    def post(self, request):
        dict_data = json.loads(request.body.decode())
        sku_id = dict_data.get("sku_id")
        user = request.user

        if not sku_id:
            return http.HttpResponseForbidden("参数不全")
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.HttpResponseForbidden("商品不存在")

        redis_conn = get_redis_connection("history")
        pipeline = redis_conn.pipeline()

        pipeline.lrem("history_%s" % user.id, 0, sku_id)
        pipeline.lpush("history_%s" % user.id, sku_id)
        pipeline.ltrim("history_%s" % user.id, 0, 4)
        pipeline.execute()

        return http.JsonResponse({"code": RET.OK, "errmsg": "ok"})


    def get(self, request):
        redis_conn = get_redis_connection("history")
        user = request.user
        sku_ids = redis_conn.lrange("history_%s" % user.id, 0, 4)

        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                "id": sku.id,
                "name": sku.name,
                "price": sku.price,
                "default_image_url": sku.default_image_url.url
             }
            sku_list.append(sku_dict)

        return http.JsonResponse({"skus": sku_list})


class UserFindPasswordView(View):
    def get(self, request):
        return render(request, "find_password.html")


class UserFindPasswordFirstStepView(View):
    def get(self, request, username):
         # username = request.GET.get("username")
        print(username)
        # img_code = request.GET.get("text")
        # img_code_id = request.GET.get("image_code_id")
        #
        # redis_con = get_redis_connection("code")
        # redis_image_code = redis_con.get("image_code_%s" % img_code_id)
        # if img_code != redis_image_code:
        #     return http.JsonResponse({"status": "4001"})

        try:
            if re.match(r'^1[3-9]\d{9}$', username):
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except User.DoesNotExist:
            return http.JsonResponse({"status": "401"})

        else:
            context = {
                "mobile": user.mobile,
            }

        return http.JsonResponse(context)


class UserFindPasswordSecondStepView(View):
    def get(self, request, username):
        sms_code = request.GET.get("sms_code")

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            return http.JsonResponse({"status": "404"})
        print(user)
        mobile = user.mobile
        redis_conn = get_redis_connection("code")
        set_code = redis_conn.get("sms_code_%s" % mobile)
        print(set_code)
        if sms_code != (set_code.decode()):
            return http.JsonResponse({"status": "401"})

        context = {
            "user_id": user.id,
            "access_token": 1
        }


        return http.JsonResponse(context)



class UserFindPasswordSMSView(View):

    def get(self, request):
        mobile = request.GET.get("mobile")

        sms_code = "%06d" % random.randint(0, 999999)

        print(sms_code)

        redis_con = get_redis_connection("code")

        ccp = CCP()
        ccp.send_template_sms(mobile, [sms_code, contants.REDIS_SMS_CODE_EXPIRES / 60], 1)

        pipeline = redis_con.pipeline()
        pipeline.setex("sms_code_%s" % mobile, contants.REDIS_SMS_CODE_EXPIRES, sms_code)
        pipeline.setex("send_flag_%s" % mobile, contants.REDIS_SEND_FLAG_EXPIRES, 1)
        pipeline.execute()


        return http.JsonResponse({"errmsg": "发送成功", "code": RET.OK})


class UserFindPassword3thView(View):
    def post(self, request, user_id):
        password = request.POST.get("password")
        password2 = request.POST.get("password2")
        access_token = request.POST.get("access_token")

        if not all([password, password2]):
            return http.JsonResponse({"status": "400"})

        if password != password2:
            return http.JsonResponse({"status": "404"})

        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return http.JsonResponse({"status": "401"})

        user.set_password(password)
        user.save()

        return http.JsonResponse({"code": "OK"})



